<template>
  <div class="wh-tdt-wraper">
    <div class="wh-tdt" id="wh-map-component-tiandi"></div>
    <div class="wh-tdt-infoWindow" ref="wh-tdt-infoWindow">
      <div class="wh-tdt-infoWindow-title">
        <p>
          {{currentInfo.title || '提示'}}
        </p>
        <img @click="onCloseInfoWindow" src="../assets/close.png" alt="">
      </div>
      <div class="wh-tdt-infoWindow-content">
        {{currentInfo.content || '内容'}}
      </div>
      <div class="wh-tdt-infoWindow-bottom"></div>
    </div>
  </div>
</template>

<script>
import loadScript from '../common/loadScript.js'
export default {
  data() {
    return {
      map: '',
      navgList: [],
      pathArr: [],
      pointArr: [],
      config: null,
      infoWindow: null,
      currentInfo: {}
    }
  },
  props: {
    loadedMap: {
      type: Function,
      default: null
    },
  },
  mounted() {
  },
  methods: {
    loadMap (options) {
      console.log('创建天地图');
      return new Promise((resolve, reject) => {
        if(!options.loadConfig) {
          console.error('未配置地图加载所需的必要配置');
          reject('未配置地图加载所需的必要配置')
        }
        if (!options.loadConfig.key) {
          console.warn('未配天地图key')
          reject('未配置天地图key')
        }
        const apiHost = 'http://api.tianditu.gov.cn/api'
        const version = options.loadConfig.version || '4.0'
        const key = options.loadConfig.key
        const url = options.loadConfig.customUrl?options.loadConfig.customUrl:`${apiHost}?v=${version}&tk=${key}`


        loadScript('T', url).then(res => {

          const mapConfig = options.mapConfig?options.mapConfig:{}
          var map = new T.Map('wh-map-component-tiandi', {
            center: mapConfig.center?T.LngLat(mapConfig.center[0], mapConfig.center[1]):null,
            minZoom: mapConfig.minZoom || null,
            maxZoom: mapConfig.maxZoom || null,
            zoom: mapConfig.zoom || null,
          });
          //创建自定义图层对象
          if (options.loadConfig.tileUrl) {
            var lay = new T.TileLayer(options.loadConfig.tileUrl);
            //将图层增加到地图上
            map.addLayer(lay);
          }
          //  设置边界
          if (mapConfig.bounds && mapConfig.bounds.length === 2) {
            const bounds = new T.LngLatBounds(new T.LngLat(options.mapConfig.bounds[0][0], options.mapConfig.bounds[0][1]), new T.LngLat(options.mapConfig.bounds[1][0], options.mapConfig.bounds[1][1]));
            map.setMaxBounds(bounds);
          }
          this.map = map
          this.map.on('click', this.onClickMap)
          this.initInfoWindow()
          this.loadedMap(this.map)
          resolve(map)
        })
      })
    },
    initInfoWindow () {
      this.infoWindow = new T.InfoWindow('', {
        autoPan: true,
        closeButton: false,
        closeOnClick: true,
        offset: new T.Point(0, -45)
      });
    },
    loadMarker (markerList) {
      console.log('加载 marker');

      for (var i = 0; i < markerList.length; i++) {
        var markerOptions = markerList[i].options?markerList[i].options:{}
        var size = [markerOptions.width||28, markerOptions.height||28]
        var offset = [size[0]/2, size[1]]
        var icon = new T.Icon({
          iconUrl: markerOptions.icon || require('../assets/marker/marker-6.png'),
          iconSize: new T.Point(size[0], size[1]),
          iconAnchor: new T.Point(offset[0], offset[1])
        })
        markerOptions.icon = icon
        markerOptions.zIndexOffset = markerOptions.zIndex || 0
        markerOptions.opacity = markerOptions.opacity || 1

        for (var j = 0; j < markerList[i].list.length; j++) {
          var marker = new T.Marker(new T.LngLat(markerList[i].list[j].position[0], markerList[i].list[j].position[1]), {
            ...markerOptions
          });
          marker.properties = {
            showInfoWindow: markerOptions.showInfoWindow,
            customInfoWindow: markerOptions.customInfoWindow,
            ...markerList[i].list[j].properties
          }
          marker.on('click', this.onClickMarker)
          this.map.addOverLay(marker)
        }
      }
    },
    loadPolygon (polygonList) {
      console.log(' 创建 polygon');
      // color: polygonList[i].polygonOptions.color || '#0000FF',
      // weight: polygonList[i].polygonOptions.weight || 3,
      // opacity: polygonList[i].polygonOptions.opacity || 0.5,
      // fillColor: polygonList[i].polygonOptions.fillColor || '#0000FF',
      // fillOpacity: polygonList[i].polygonOptions.fillOpacity || 0.2,
      // lineStyle: polygonList[i].polygonOptions.lineStyle || 'solid'

      for (var i = 0; i < polygonList.length; i++) {
        var polygonOptions = polygonList[i].options?polygonList[i].options:{}
        polygonOptions.color = polygonOptions.lineColor || '#00D3FC'
        polygonOptions.weight = polygonOptions.lineWidth || 2
        polygonOptions.lineStyle = polygonOptions.lineStyle || 'solid'
        polygonOptions.fillOpacity = polygonOptions.opacity || 0.5
        polygonOptions.opacity = polygonOptions.lineOpacity || 1
        polygonOptions.fillColor = polygonOptions.color || '#00D3FC'
        const path = this.getPath(polygonList[i].path)
        var polygon = new T.Polygon(path, polygonOptions);
        polygon.properties = {
          showInfoWindow: polygonOptions.showInfoWindow,
          customInfoWindow: polygonOptions.customInfoWindow,
          ...polygonList[i].properties
        }
        polygon.on('click', this.onClickPolygon)
        this.map.addOverLay(polygon)
      }
    },
    loadSpecialPath (config) {
    },
    loadPath (config) {
      console.log('加载路径');
      this.pathArr = []
      this.pointArr = []
      this.config = config

      var options = config.options?config.options:{}
      // 起点
      var startSymbol = {
        icon: require('../assets/marker/start.png'),
        width: 28,
        height: 28
      }
      if (options.start && options.start.icon) {
        startSymbol.icon = options.start.icon
      }
      if (options.start && options.start.width) {
        startSymbol.width = options.start.width
      }
      if (options.start && options.start.height) {
        startSymbol.height = options.start.height
      }
      // 终点
      var endSymbol = {
        icon: require('../assets/marker/end.png'),
        width: 28,
        height: 28
      }
      if (options.end && options.end.icon) {
        endSymbol.icon = options.end.icon
      }
      if (options.end && options.end.width) {
        endSymbol.width = options.end.width
      }
      if (options.end && options.end.height) {
        endSymbol.height = options.end.height
      }
      // 图标
      var pointSymbol = {
        icon: require('../assets/marker/car.png'),
        width: 28,
        height: 28
      }
      if (options.point && options.point.icon) {
        pointSymbol.icon = options.point.icon
      }
      if (options.point && options.point.width) {
        pointSymbol.width = options.point.width
      }
      if (options.point && options.point.height) {
        pointSymbol.height = options.point.height
      }
      //  线条样式
      var pathStyle = {
        color: 'red',
        width: 5,
        defaultColor: '#00D3FC',
        speed: 80 // m/s
      }
      if (options.line && options.line.defaultColor) {
        pathStyle.defaultColor = options.line.defaultColor
      }
      if (options.line && options.line.width) {
        pathStyle.width = options.line.width
      }
      if (options.line && options.line.color) {
        pathStyle.color = options.line.color
      }
      if (options.speed) {
        pathStyle.speed = options.speed
      }
      let startIcon = new T.Icon({
        iconUrl: startSymbol.icon,
        iconSize: new T.Point(startSymbol.width, startSymbol.height),
        iconAnchor: new T.Point(startSymbol.width/2, startSymbol.height)
      });
      let pointIcon = new T.Icon({
        iconUrl: pointSymbol.icon,
        iconSize: new T.Point(pointSymbol.width, pointSymbol.height),
        iconAnchor: new T.Point(pointSymbol.width/2, pointSymbol.height/2)
      });
      let endIcon = new T.Icon({
        iconUrl: endSymbol.icon,
        iconSize: new T.Point(endSymbol.width, endSymbol.height),
        iconAnchor: new T.Point(endSymbol.width/2, endSymbol.height)
      });
      for (var i = 0; i < config.list.length; i++) {

        let startMarker = new T.Marker(new T.LngLat(config.list[i].path[0][0], config.list[i].path[0][1]),
        {
          icon: startIcon,
        });
        startMarker.properties = {
          index: i
        }
        this.map.addOverLay(startMarker);
        // startMarker.on('click', (e) => {
        //   this.onClickPoint(e, pathStyle)
        // })


        let pointMarker = new T.Marker(new T.LngLat(config.list[i].path[0][0], config.list[i].path[0][1]),
        {
          icon: pointIcon,
        });
        pointMarker.properties = {
          index: i
        }
        this.map.addOverLay(pointMarker);
        pointMarker.on('click', (e) => {
          this.onClickPoint(e, pathStyle)
        })

        this.pointArr.push(pointMarker)

        let endMarker = new T.Marker(new T.LngLat(config.list[i].path[config.list[i].path.length - 1][0], config.list[i].path[config.list[i].path.length - 1][1]),
        {
          icon: endIcon,
        });
        this.map.addOverLay(endMarker);

        var pathPointArr = this.getPath(config.list[i].path)
        let path = new T.Polyline(pathPointArr, {
          color: pathStyle.defaultColor,
          weight: pathStyle.width
        });
        this.map.addOverLay(path);
        this.pathArr.push(path)
      }

      // loadScript('D3', 'http://cdn.bootcss.com/d3/3.5.17/d3.js').then(() => {
      //   loadScript('T.D3SvgOverlay', 'http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/D3SvgOverlay.js').then(() => {
      //     loadScript('T.CarTrack', 'http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/CarTrack.js').then(() => {
      //       if (config.list) {
      //         var arr = []
      //         config.list.forEach(ele => {
      //           var pathArr = []
      //           ele.path.forEach(item => {
      //             var point = new T.LngLat(item[1], item[0])
      //             pathArr.push(point)
      //           })
      //           arr.push({
      //             ...ele,
      //             path: pathArr
      //           })
      //         })
      //         for (var i = 0; i < arr.length; i++) {
      //           this.createRoute(arr[i], config.options?config.options:{})
      //         }
      //       } else {
      //         var configDriving = {
      //           policy: 0,	//驾车策略
      //           onSearchComplete: this.searchResult	//检索完成后的回调函数
      //         };
      //         var drivingRoute = new T.DrivingRoute(this.map, configDriving);

      //         var startLngLat = new T.LngLat(112.54, 37.83);
      //         var endLngLat = new T.LngLat(112.58, 37.73);
      //         //驾车路线搜索
      //         drivingRoute.search(startLngLat, endLngLat);
      //       }

      //     })
      //   })
      // })




    },
    onClickPoint (e, pathStyle) {
      alert('天地图暂不支持路径回放')
      console.log('天地图暂不支持路径回放');
      // let index = e.target.properties.index
      // var currentPoint = this.pointArr[index]
      // var currentPath = this.pathArr[index]
      // console.log(currentPath.getLngLats());
      // var distance = this.getDistance(currentPath.getLngLats())
      // var time = distance / pathStyle.speed
    },
    getDistance(points) {
      var r = 0;
      for (var k = 0; k < points.length - 1; k++) {
          r += points[k].distanceTo(points[k + 1]);
      }
      return r;
    },
    searchResult (result) {

      var routes = result.getNumPlans()
      console.log(routes);
      for (var i = 0; i < routes; i++) {
        //获得单条驾车方案结果对象
        var plan = result.getPlan(i);
        console.log(plan.getPath());
        this.createRoute({
          name: '',
          path: plan.getPath()
        }, {
          startIcon: 'http://lbs.tianditu.gov.cn/images/bus/start.png',
          endIcon: 'http://lbs.tianditu.gov.cn/images/bus/end.png'
        });
      }

    },
    createRoute (obj, options) {
      console.log(obj);

      var carstyle = {
        iconUrl: require('../assets/marker/car.png'),
        width: 28,
        height: 28
      }
      if (options.point && options.point.icon) {
        carstyle.iconUrl = options.point.icon
      }
      if (options.point && options.point.width) {
        carstyle.width = options.point.width
      }
      if (options.point && options.point.height) {
        carstyle.height = options.point.height
      }
      var polylinestyle = {
        display: true,
        color: '#00D3FC',
        width: 5,
        opacity: 1
      }
      if (options.line && options.line.defaultColor) {
        polylinestyle.color = options.line.defaultColor
      }
      if (options.line && options.line.width) {
        polylinestyle.width = options.line.width
      }
      var _CarTrack = new T.CarTrack(this.map, {
        interval: options.interval || 100,
        speed: options.speed || 10,
        dynamicLine: false,
        Datas: obj.path,
        carstyle: carstyle,
        polylinestyle: polylinestyle
      })
      // this.navgList.push({
      //   index: index,
      //   obj: _CarTrack
      // })

      // this.createStartMarker(obj, index, renderOptions)
      // 起点
      var startSymbol = {
        icon: require('../assets/marker/start.png'),
        width: 28,
        height: 28
      }
      if (options.start && options.start.icon) {
        startSymbol.icon = options.start.icon
      }
      if (options.start && options.start.width) {
        startSymbol.width = options.start.width
      }
      if (options.start && options.start.height) {
        startSymbol.height = options.start.height
      }
      var startMarker = new T.Marker(obj.path[0], {
        icon: new T.Icon({
            iconUrl: startSymbol.icon,
            iconSize: new T.Point(startSymbol.width, startSymbol.height),
            iconAnchor: new T.Point(startSymbol.width/2, startSymbol.height)
        })
      });
      startMarker.on('click', (e) => {
        _CarTrack.start()
      })
      this.map.addOverLay(startMarker);
      // 终点
      var endSymbol = {
        icon: require('../assets/marker/end.png'),
        width: 28,
        height: 28
      }
      if (options.end && options.end.icon) {
        endSymbol.icon = options.end.icon
      }
      if (options.end && options.end.width) {
        endSymbol.width = options.end.width
      }
      if (options.end && options.end.height) {
        endSymbol.height = options.end.height
      }
      var endMarker = new T.Marker(obj.path[obj.path.length - 1], {
        icon: new T.Icon({
            iconUrl: endSymbol.icon,
            iconSize: new T.Point(endSymbol.width, endSymbol.height),
            iconAnchor: new T.Point(endSymbol.width/2, endSymbol.height)
        })
      });
      this.map.addOverLay(endMarker);

    },
    getPath (arr) {
      var newArr = []
      for (var i = 0; i < arr.length; i++) {
        newArr.push(new T.LngLat(arr[i][0],arr[i][1]))
      }
      return newArr
    },
    onCloseInfoWindow () {
      this.infoWindow.closeInfoWindow();
      this.currentInfo = {}
    },
    onClickMarker (e) {
      this.currentInfo = e.target.properties

      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-tdt-infoWindow'])
        }
        this.map.openInfoWindow(this.infoWindow, e.lnglat)
      }
      this.$emit('on-click-marker', e, this.currentInfo, this.infoWindow)
    },
    onClickPolygon (e) {
      this.currentInfo = e.target.properties
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-tdt-infoWindow'])
        }
        this.map.openInfoWindow(this.infoWindow, e.lnglat)
      }
      this.$emit('on-click-polygon', e, this.currentInfo, this.infoWindow)
    },
    onClickMap (e) {
      console.log('点击了地图');
      this.$emit('on-click-map', e)
    }
  },
}
</script>

<style scoped>
  .wh-tdt-wraper {
    width: 100%;
    height: 100%;
  }
  .wh-tdt {
    width: 100%;
    height: 100%;
  }
  .wh-tdt-infoWindow {
    width: 300px;
    background: rgba(39,40,34, 0.8);
    left: -1000px;
    box-sizing: border-box;
    border-radius: 5px;
    overflow: hidden;
  }
  .wh-tdt-infoWindow-title {
    padding: 10px 16px;
    box-sizing: border-box;
    background: rgba(27,29,25, 0.8);
    color: #dbdbdb;
    font-weight: 500;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  .wh-tdt-infoWindow-title>p {
    flex-shrink: 0;
    font-size: 16px;
    margin: 0;
  }
  .wh-tdt-infoWindow-title>img {
    flex-shrink: 1;
    width: 20px;
    display: block;
    cursor: pointer;
  }
  .wh-tdt-infoWindow-content {
    padding: 10px 16px;
    box-sizing: border-box;
    color: #dbdbdb;
    text-align: left;
    font-weight: 400;
  }
  .wh-tdt-infoWindow-bottom {
    position: absolute;
    left: 50%;
    bottom: -40px;
    margin-left: -20px;
    width: 0;
    height: 0;
    border-top: 20px solid rgba(39,40,34, 0.8);
    border-right: 20px solid transparent;
    border-left: 20px solid transparent;
    border-bottom: 20px solid transparent;
  }
  >>> .tdt-infowindow-tip-container {
    display: none;
  }
  >>> .tdt-infowindow-content-wrapper {
    padding: 0;
    background: transparent;
    box-shadow: none;
  }
  >>> .tdt-infowindow-content {
    margin: 0;
    height: auto;
    background: transparent;
  }
  >>> .tdt-infowindow-content p {
    margin: 0;
  }
  >>> .tdt-control-copyright {
    display: none !important;
  }

</style>
